package com.idp.system.utils;

import com.idp.system.dto.SysButtonDto;
import com.idp.system.dto.SysMenuDto;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 菜单工具类
 *
 * @author king
 *
 */
public class MenuUtil {

	/** 菜单根目录标识 */
	private static final String MENU_ROOT = "0";
	
	/**
	 * 
	 * 获取树形结构菜单
	 *
	 * @author king
	 * 
	 * @param menuList
	 * @return
	 */
	public static List<SysMenuDto> getMenusForTree(List<SysMenuDto> menuList){
		
		if(menuList != null) {
			
			return getChildren(menuList, MENU_ROOT);
		}
		
		return null;
	}
	
	/**
	 * 
	 * 获取子节点
	 *
	 * @author king
	 * 
	 * @param menuList
	 * @param parentId
	 * @return
	 */
	private static List<SysMenuDto> getChildren(List<SysMenuDto> menuList, String parentId){
		
		if(menuList != null) {
			
			List<SysMenuDto> children = new ArrayList<SysMenuDto>();
			
			for(SysMenuDto sysMenuDto : menuList) {
				
				if(parentId.equals(sysMenuDto.getParentId())) {
					
					sysMenuDto.setChildren(getChildren(menuList, sysMenuDto.getId()));
					children.add(sysMenuDto);
				}
			}
			
			if(children.size() > 0) {
				
				return children;
			}
		}
		
		return null;
	}
	
	/**
	 * 
	 * 获取所有菜单选中的按钮
	 *
	 * @author king
	 * 
	 * @param menus
	 * @return
	 */
	public static List<SysButtonDto> getButtonsFromMenuTree(List<SysMenuDto> menus){
		
		List<SysButtonDto> buttons = new ArrayList<SysButtonDto>();
		
		getButtonsFromMenuChildren(menus, buttons);
		
		return buttons;
	}
	
	/**
	 * 
	 *  获取下级菜单选中的按钮
	 *
	 * @author king
	 * 
	 * @param menus
	 * @param buttons
	 */
	private static void getButtonsFromMenuChildren(List<SysMenuDto> menus,List<SysButtonDto> buttons) {
		
		if(menus != null && menus.size() > 0) {
			
			for(SysMenuDto menu : menus) {
				
				List<SysButtonDto> buttonList = menu.getButtons();
				
				if(buttonList != null && buttonList.size() > 0) {
					
					for(SysButtonDto button : buttonList) {
						
						if(button.getChecked() != null && button.getChecked()) {
							
							buttons.add(button);
						}
					}
				}
				
				List<SysMenuDto> children = menu.getChildren();
				
				if(children != null && children.size() > 0) {
					getButtonsFromMenuChildren(children, buttons);
				}
			}
		}
	}
	
	/**
	 * 
	 * 选中菜单中有权限的按钮
	 *
	 * @author king
	 *
	 */
	public static void selectedButtonForMenuTree(List<SysMenuDto> menus, List<String> buttonIds) {
		
		if(menus != null && menus.size() > 0 && buttonIds != null && buttonIds.size() > 0) {
			
			for(SysMenuDto menu : menus) {
				
				List<SysButtonDto> buttonList = menu.getButtons();
				
				if(buttonList != null && buttonList.size() > 0) {
					
					for(SysButtonDto button : buttonList) {
						
						if(buttonIds.contains(button.getId())) {
							
							button.setChecked(true);
						}
					}
				}
			}
		}
	}
}
